package com.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DB {

	private static String DB_CONNECTION_STRING;

	private static String DB_Username;

	private static String DB_PASSWORD;

	public static void init(String connStr, String user, String pass) { 
		DB_CONNECTION_STRING = connStr;
		DB_Username = user;
		DB_PASSWORD = pass;
	}
	
	public static Connection dbConnection;

	public static void connectToDB() throws ClassNotFoundException, SQLException {
		Class.forName("oracle.jdbc.driver.OracleDriver");
		dbConnection = DriverManager.getConnection(DB_CONNECTION_STRING, DB_Username, DB_PASSWORD);
	}
	
	public static void disconectFromDB() throws SQLException {
		if (dbConnection != null) {
			dbConnection.close();
		}
	}	
	
	public static String select(String column, String table, String conditionColumn, String conditionValue, Connection dbConn) throws SQLException {
		Statement stmtSelect = null;
		ResultSet result = null;
		try {
			stmtSelect = dbConn.createStatement();
			result = stmtSelect.executeQuery("select " + column + " from " + table + " where " + conditionColumn + " = '" + conditionValue + "'");
			if (result.next()) {
				String res = result.getString(column);
				return res;
			} else {
				return "";
			}
		} finally {
			if (stmtSelect != null) {
				stmtSelect.close();
			}
			if (result != null) {
				result.close();
			}
		}
	}
	
	public static String select(String query, String[] getStringParams, Connection dbConn) throws SQLException {
		Statement stmtSelect = null;
		ResultSet result = null;
		try {
			stmtSelect = dbConn.createStatement();
			result = stmtSelect.executeQuery(query);
			if (result.next()) {
				String res = "";
				for (String str:getStringParams) {
					res += " " + result.getString(str); 
				}
				return res;
			} else {
				return "";
			}
		} finally {
			if (stmtSelect != null) {
				stmtSelect.close();
			}
			if (result != null) {
				result.close();
			}
		}
	}
	
	public static String select(String query, Connection dbConn) throws SQLException {
		Statement stmtSelect = null;
		ResultSet result = null;
		try {
			stmtSelect = dbConn.createStatement();
			result = stmtSelect.executeQuery(query);
			int columns = result.getMetaData().getColumnCount();
			if (result.next()) {
				String res = "";
				for (int i = 1; i <= columns; i++) {
					res += " " + result.getString(i); 
				}
				return res;
			} else {
				return "";
			}
		} finally {
			if (stmtSelect != null) {
				stmtSelect.close();
			}
			if (result != null) {
				result.close();
			}
		}
	}
}
